import { reactive, watch, getCurrentInstance } from 'vue'
import { cloneDeep } from 'lodash-es'
import { TableColumnProps } from '#/antd'

export function useCheckState(tableColumns: TableColumnProps[]) {
  const ctx = getCurrentInstance()
  const plainOptions = tableColumns.map((column) => {
    return {
      label: column.title,
      key: column.dataIndex,
      checked: true,
    }
  })
  const initData = cloneDeep(plainOptions)
  const checkBoxState = reactive({
    indeterminate: false,
    checkAll: true,
    plainOptions: plainOptions,
  })

  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  const onCheckAllChange = (e: any) => {
    checkBoxState.plainOptions.forEach(
      (item) => (item.checked = e.target.checked)
    )
    checkBoxState.indeterminate = false
  }

  const resetCheck = () => {
    checkBoxState.plainOptions.forEach((_, index) => {
      checkBoxState.plainOptions[index] = cloneDeep(initData[index])
    })
  }

  // 监听当前选中列表是否变化
  watch(checkBoxState.plainOptions, (val) => {
    const checkedList = val.filter((item) => {
      return item.checked
    })

    checkBoxState.indeterminate =
      !!checkedList.length &&
      checkedList.length < checkBoxState.plainOptions.length
    checkBoxState.checkAll =
      checkedList.length === checkBoxState.plainOptions.length

    // // 根据选中列表筛选排序得到当前表格列数据
    const currrentColumn: TableColumnProps[] = []
    checkedList.forEach((check) => {
      const item = tableColumns.find((column) => column.dataIndex === check.key)
      item && currrentColumn.push(item)
    })

    ctx?.emit('update:tableColumns', currrentColumn)
  })

  return { checkBoxState, onCheckAllChange, resetCheck }
}
